Lesson 4 - beginner exercise

For each scenario suggested below create the corresponding set of if statments. If you are finding it difficult you should create a truth tree diagram.


balance = 200
stock = 3
price = 50
def withdrawCash(amount):
	if balance - amount < 0: return False
	else: return True

def buyItem():
	# will use widthdrawCash to see if they have enough money
	# will also test to make sure ther is stock
	# if both conditions are true then it will subtract price from balance
	# and one from stock!
	
buyItem()
buyItem()
buyItem() # should print an error

Suggested change- Read the comments and add if statements to buyItem()

Toggle answer

username = "bob"
password = "pass"
failedAttempt = 0

def allowLogon(user, pass):
	# will print "logged on" if user and pass match
	# if they do not then a error is printed and failedAttempt is increments
	# finally log on will always be disallowed if failed attempts >= 3

allowLogon("bob", "monkey")
allowLogon("bob", "passy")
allowLogon("bob", "punk")
allowLogon("bob", "pass") # will also fail even though correct!

 

Suggested change - Pay attention to the failed attemp

Toggle answer

teamAScore = 0
teamBScore = 0

def isGoal(inNet, offside, team):
	# if isNet is true and offside is false then they score
	# it will then add 1 to the correct teams score!
	
isGoal(True, True, "A")
isGoal(True, False, "A")
isGoal(False, False, "B")
isGoal(True, False, "B")
isGoal(True, False, "A")

print teamAScore # should be 2
print teamBScore #  should be 1

Suggested changes - Make sure you test for the team name! This could get very complicated as there are a fair few possibilities./ However not all of them are used!

Toggle answer